/**
 * This file is part of the FlexiTimer project.
 * 
 * Author: Florian Arndt <f.aarndt@web.de>
 *  	   Clemens Teichmann <>
 *
 * http://code.google.com/p/flexitimer/ 
 */

package flexitimer_client.calc;

import java.awt.event.ActionEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.AbstractAction;

import flexitimer_client.gui.frame;
import flexitimer_client.gui.optionFrame;

public class endTimeAction extends AbstractAction {


	public endTimeAction() {
		super("Arbeitszeit ausgeben");
	}

	@SuppressWarnings("deprecation")
	public void actionPerformed(ActionEvent e) {
	    //SimpleDateFormat sdfa = new SimpleDateFormat("HH:mm a");
	    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
	    Date startTime = null;
	    Date endTime = null;
	    Date workTime = null;
	    int difHour1;
	    int difMin1 = 0;
	    int difHour2;
	    int difMin2 = 0;
	    Date maxTime = null;
	    Date normalTime = null;
	 
	    try {
			startTime = sdf.parse(frame.getInstance().getStartTime());
			endTime = sdf.parse(frame.getInstance().getEndTime());
			workTime = sdf.parse("00:00");
			maxTime = sdf.parse(optionFrame.getInstance().getMaxTime());
			normalTime = sdf.parse(optionFrame.getInstance().getMinTime());
			workTime.setHours(endTime.getHours() - startTime.getHours());
			workTime.setMinutes(endTime.getMinutes() - startTime.getMinutes());
			
			difHour1 = maxTime.getHours() - workTime.getHours();
			difMin1 = maxTime.getMinutes() - workTime.getMinutes();
			
			boolean add = false;
			String time;
			if(workTime.getTime() > normalTime.getTime()) {
				difHour2 = workTime.getHours() - normalTime.getHours();
				difMin2 = workTime.getMinutes() - normalTime.getMinutes();
				add = true;
			} else {
				difHour2 = normalTime.getHours() - workTime.getHours();
				difMin2 = normalTime.getMinutes() - workTime.getMinutes();
			}
			
			if(workTime.getTime() > maxTime.getTime()) {
				difHour1 = 0;
				difMin1 = 0;
			}
			
			if(difMin1 < 0) {
				difHour1 -= 1;
				difMin1 = 60 + difMin1;
			}
			if(difMin2 < 0) {
				difHour2 -= 1;
				difMin2 = 60 + difMin2;
			}
			
			if (difHour2 >= 2 && difMin2 > 12 && add == true) {
				difHour2 = 2;
				difMin2 = 12;
			}
			
			if(add == true) {
				time = difHour2 + ":" + String.format("%02d", difMin2);
			} else {
				time = "-" + difHour2 + ":" + String.format("%02d", difMin2);
			}
			
			frame.getInstance().addText("Heute gearbeitet: " + workTime.getHours() + ":" + 
					String.format("%02d", workTime.getMinutes()) + 
					" \nAuf Stundenkonto: " + time +
					" \nVerschenkte Zeit (10.5h): " + difHour1 + ":" +
					String.format("%02d", difMin1));
		} catch (ParseException e1) {
			frame.getInstance().addText("ERROR: Zeit falsch eingegeben! (hh:mm)");
		}
	}
}
